/**
 * poi兴趣点查询定位widget author Anpt
 * 
 */
define([ "require", "dojo/_base/declare", "dojo/_base/lang",
    "dojo/_base/array", "dojo/_base/fx", "dojo/fx/easing",
    "../../util/ajaxUtil", "../../util/WKTUtil", "dojo/dom", "dojo/dom-attr",
    "dojo/dom-class", "dojo/dom-style", "dojo/on", "dojo/query", "dojo/topic",
    "../BaseWidget", "esri/geometry/Point", "esri/geometry/screenUtils",
    "esri/graphic", "dijit/layout/ContentPane", "esri/layers/GraphicsLayer",
    "esri/SpatialReference", "esri/geometry/Polygon", "esri/geometry/Polyline",
    "esri/geometry/webMercatorUtils", "esri/InfoTemplate",
    "esri/symbols/PictureMarkerSymbol", "esri/symbols/SimpleLineSymbol",
    "esri/symbols/SimpleFillSymbol", "esri/symbols/SimpleMarkerSymbol",
    "esri/SpatialReference", "esri/Color",
    "gistech/widgets/QueryTableList/QueryTableList",
    "dojo/text!./templates/Template.html" ], function(require, declare, lang,
    array, baseFx, easing, ajaxUtil, WKTUtil, dom, domAttr, domClass, domStyle,
    on, query, topic, BaseWidget, Point, screenUtils, Graphic, ContentPane,
    GraphicsLayer, SpatialReference, Polygon, Polyline, webMercatorUtils,
    InfoTemplate, PictureMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol,
    SimpleMarkerSymbol, SpatialReference, Color, QueryTableList, template) {
	return declare([ BaseWidget ], {
	  templateString : template,
	  map : null,
	  keyword : null,
	  righttabCon : null,
	  handls : [],
	  lefttabCom : null,
	  constructor : function(args) {
		  this.map = args.map;
		  this.searchType = args.searchtype;
		  this.citycode = args.citycode;
		  this.tableFields = ioc.poiSearch[this.searchType].tableField;
		  this.advQueryTableColumnsData = [];
		  for ( var i = 0, k = this.tableFields.length; i < k; i++) {
			  if (this.tableFields[i].field != 'geometry')
				  this.advQueryTableColumnsData.push(this.tableFields[i]);
		  }
		  this.graphicLayer = new GraphicsLayer({
			  id : "PoiSearchLayer"
		  });
		  this.advQueryTableSortName = ioc.poiSearch[this.searchType].sortField;
		  this.advQueryTableSortOrder = ioc.poiSearch[this.searchType].sortOrder;
		  this.keyword = args.keyWord;
		  // 存储所有graphic图层
		  ioc.map.graphiclayers.push(this.graphicLayer);
	  },
	  postCreate : function() {
		  this.inherited(arguments);
		  this.topicSubscribe = topic.subscribe("locatorByNS", lang.hitch(this,
		      this.locationByNS));
		  on(this.closebtn2,"click",lang.hitch(this,this.closeDialog));
	  },
	  startup : function() {
		  this.inherited(arguments);
		  this.init();
	  },
	  init : function() {
		  if (ioc.poiSearch[this.searchType].type == 'poi') {
			  this.geoqSearch();
		  } else if (ioc.poiSearch[this.searchType].type == 'mapserver') {
			  this.mapServerSearch();
		  }
	  },
	  locationByNS : function(e) {
		  obj = e.attr;
		  var geo = null;
		  var symbol = null;
		  if (obj.geometryType == "esriGeometryPoint") {
			  geo = new Point($.parseJSON(obj.geometry));
			  symbol = new PictureMarkerSymbol(
			      "gistech/widgets/PoiSearchWidget/images/lb1.png", 30, 30);
			  symbol.setOffset(1, 13);
		  } else if (obj.geometryType == "esriGeometryPolygon") {
			  geo = new Polygon($.parseJSON(obj.geometry));
			  symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
			      new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT, new Color([
			          255, 0, 0 ]), 2), new Color([ 255, 255, 0, 0.25 ]));
		  } else if (obj.geometryType == "esriGeometryPolyline") {
			  geo = new Polyline($.parseJSON(obj.geometry));
			  symbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASH, new Color([
			      255, 0, 0 ]), 4);
		  }
		  var template = "";
		  Object.getOwnPropertyNames(obj)
		      .forEach(
		          function(field) {
			          if ([ "SHAPE", "SHAPE_LENGTH", "SHAPE_AREA", "GEOMETRYTYPE","SHAPE.LEN","SHAPE.AREA",
			              "GEOMETRY" ,"TYPECODE","OBJECTID"].indexOf(field.toUpperCase())>-1) {
				          return;
			          }
			          var value = '${' + field	+ '}';
			          if(field.toUpperCase().indexOf("CITYCODE")!=-1){
			        	  value = $(".city-con .city").text();
			          }
			          var fieldCN = field;
			          if(poiSearchResultFieldCNTable.hasOwnProperty(field)){
			        	  fieldCN = poiSearchResultFieldCNTable[field];
			          }
			          template += '<tr><td>' + fieldCN + '</td><td>' + value
			              + '</td></tr>';
		          });
		  template = "<table class='layerInfo'>"+template+"</table>";
		  var graphic = new Graphic(geo, symbol, obj, new InfoTemplate(obj.name,
		      template));
		  /*
			 * var graphic = new Graphic( geo, symbol, obj, new InfoTemplate(
			 * obj.name, "<tr>名称: <td>${name}</td></tr><br><tr>地址: <td>${address}</td></tr><br><tr>类型:
			 * <td>${typename}</td></tr>"));
			 */
		  this.graphicLayer.clear();
		  this.graphicLayer.add(graphic);
		  this.map.addLayer(this.graphicLayer);
		  if (obj.geometryType == 'esriGeometryPolygon'
		      || obj.geometryType == 'esriGeometryPolyline') {
			  this.map.setExtent(geo.getExtent());
		  } else if (obj.geometryType == 'esriGeometryPoint') {
			  this.map.centerAndZoom(geo, 12);
		  }
		  this.refreshGraphic(graphic, symbol);
	  },
	  geoqSearch : function() {
		  var condition = "";
		  if (this.keyword.length <= 4) {
			  condition = "?name=";
		  } else {
			  condition = "?address=";
		  }
		  var url = 'proxy.jsp?' + ioc.poiSearch[this.searchType].url + condition
		      + this.keyword + "&citycode=" + this.citycode + "&pagesize=1000"
		      + "&f=json";
		  $.ajax({
		    type : "GET",
		    url : url,
		    success : lang.hitch(this, function(results) {
			    var resultsAll = results.results;
			    this._queryCallback(resultsAll);
		    }),
		    error : function() {
			    layer.msg("请求出错", {
				    icon : 2
			    });
		    }
		  });
	  },
	  mapServerSearch : function() {
		  serverUrls = ioc.poiSearch[this.searchType].urls;
		  serverUrls.forEach(function(serverurl) {
			  var url = 'proxy.jsp?' + serverurl.url + "/find?searchText="
			      + this.keyword + "&contains=true&searchFields=" + serverurl.fields
			      + "&sr=&layers=" + serverurl.index + "&returnGeometry=true&f=json";
			  $.ajax({
			    type : "GET",
			    url : url,
			    success : lang.hitch(this, function(results) {
			    	if(results!=""&results!=null){
			    		var resultsAll = $.parseJSON(results).results;
			    		this._queryCallback(resultsAll);
			    	}else{
			    		layer.msg("服务地址异常", {
						    icon : 2
					    });
			    	}
				    
			    }),
			    error : function() {
				    layer.msg("请求出错", {
					    icon : 2
				    });
			    }
			  });
		  }, this);
	  },
	  _queryCallback : function(results) {
		  var arr;
		  arr = [];

		  dojo.map(results, function(result) {
			  geoType = null, geo = null;
			  if (ioc.poiSearch[this.searchType].type == 'mapserver') {
				  geoType = result.geometryType;
				  geo = result.geometry;
				  layername=result.layerName;
				  result = result.attributes;
				  result.layername=layername;
			  }
			  if (ioc.poiSearch[this.searchType].type == 'poi') {
				  result["geometryType"] = 'esriGeometryPoint';
				  result["geometry"] = '{"x": ' + result["lon"] + ',"y": '
				      + result["lat"] + ',"spatialReference": {"wkid": 4326}}';
			  } else if (ioc.poiSearch[this.searchType].type == 'mapserver') {
				  result["geometryType"] = geoType;
				  result["geometry"] = JSON.stringify(geo);
			  }
			  arr.push(result);
		  }, this);
		  if (!this.queryTableList) {
			  this._createQueryTableListAndBind(arr);
		  } else {
			  this._appendQueryTableList(arr);
		  }
	  },
	  _appendQueryTableList : function(data) {
		  this.queryTableList.appendData(data);
	  },
	  _createQueryTableListAndBind : function(data) {
		  Global.currentUseFun = "poiSearch";
		  this.queryTableList = new QueryTableList({
		    "tableData" : data,
		    "columnsData" : this.advQueryTableColumnsData,
		    "sortName" : this.advQueryTableSortName,
		    "sortOrder" : this.advQueryTableSortOrder
		  });
		  this.queryTableList.startup();
		  Global.widgets["tableList"] = this.queryTableList;
		  if ($(Global.widgets.right.domNode).children(".queryList").length != 0) {
			  $(Global.widgets.right.domNode).children(".queryList").remove();
		  }
		  $('.contentBody', this.domNode).empty();
		  $('.contentBody', this.domNode).append(this.queryTableList.domNode);
		  var panel = new ContentPane();
		  $(panel.domNode).wrapInner(this.domNode);
		  Global.widgets.right.removeAllTab();
		  Global.widgets.right.addTab(panel);
		  this.setRightToolsPosition();
	  },
	  setRightToolsPosition : function() {
		  var width = $(Global.widgets.right.domNode).width();
		  $(Global.widgets.BottomArrow2.domNode).css("marginRight", width);
		  $(Global.widgets.zoombar.domNode).css("marginRight", width);
		  if (Global.widgets.BottomArrow2.toolbox) {
			  $(Global.widgets.BottomArrow2.toolbox.domNode)
			      .css("marginRight", width);
		  }
	  },
	  refreshGraphic : function(geo, symbol) {
		  geoType = geo.geometry.type;
		  var resizeInterval1, resizeInterval2;
		  var resizeTimer, resizeTime = 2000;
		  clearTimeout(resizeTimer);

		  resizeInterval1 = setInterval(function() {
			  var symbol = null;
			  if (geoType.toLowerCase() == 'polygon') {
				  symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
				      new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT, new Color([
				          0, 255, 255 ]), 2), new Color([ 0, 255, 255, 0.25 ]));
			  } else if (geoType.toLowerCase() == 'polyline') {
				  symbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
				      new Color([ 0, 255, 255, 1 ]), 3);
			  } else if (geoType.toLowerCase() == 'point') {
				  symbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE, 10,
				      new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([ 0,
				          255, 255 ]), 1), new Color([ 0, 255, 255, 0.25 ]));
			  }
			  geo.setSymbol(symbol);
		  }, 200);
		  resizeInterval2 = setInterval(function() {
			  var symbol = null;
			  if (geoType.toLowerCase() == 'polygon') {
				  symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
				      new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT, new Color([
				          255, 0, 0 ]), 2), new Color([ 255, 255, 0, 0.25 ]));
			  } else if (geoType.toLowerCase() == 'polyline') {
				  symbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASH, new Color(
				      [ 255, 0, 0 ]), 4);
			  } else if (geoType.toLowerCase() == 'point') {
				  symbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE, 10,
				      new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([
				          255, 0, 0 ]), 1), new Color([ 255, 0, 0, 0.25 ]));
			  }
			  geo.setSymbol(symbol);
		  }, 220);

		  resizeTimer = setTimeout(function() {
			  clearInterval(resizeInterval1);
			  clearInterval(resizeInterval2);
			  geo.setSymbol(symbol);// 还原图像样式
		  }, resizeTime);

		  geo.setSymbol(symbol);// 解决颜色因为延迟问题不一致
	  },
	  destroy : function() {
		  this.map.removeLayer(this.graphicLayer);
		  dojo.unsubscribe(this.topicSubscribe);
		  var widgets = this.widgets;
		  for ( var name in widgets) {
			  if (widgets[name]) {
				  widgets[name].destroy();
			  }
		  }
		  this.inherited(arguments);
	  },
	  closeDialog:function(){
			this.inherited("closeDialog",arguments);
			Global.widgets.right.expandBtn.click();
			this.destroy();
		}
	});
});